from sklearn.externals import joblib
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
from math import sqrt
import operator as opt



# with open('svm.pickle', 'rb') as fr:
#     new_svm = pickle.load(fr)
# knn=joblib.load('./templates/myApp/forecast/knn_predict.pkl')
#AQI指数，PM2.5，PM10，CO，NO2，SO2，O3  爬取顺序

#AQI	PM2.5	PM10	SO2	CO	NO2	O3_8h 需要顺序
# l = [59, 37, 66, 0.6, 20, 6, 47]
# t = l[5]
# l[5] = l[4]
# l[4] = l[3]
# l[3] = t
# print(l)
# print(knn.predict([l]))

# def get_preknn(l):
#     t = l[5]
#     l[5] = l[4]
#     l[4] = l[3]
#     l[3] = t
#     # knn = joblib.load('./myApp/forecast/knn_predict.pkl')
#     with open('./myApp/forecast/knn_predict.pkl', 'rb') as fr:
#         new_svm = pickle.load(fr)
#         mm = new_svm.predict([l])
#     # print(l)
#     # print(knn.predict([l]))
#     return mm
def normData(dataSet):
    maxVals = dataSet.max(axis=0)
    minVals = dataSet.min(axis=0)
    ranges = maxVals - minVals
    retData = (dataSet - minVals) / ranges
    return retData, ranges, minVals
def kNN(dataSet, labels, testData, k):
    distSquareMat = (dataSet - testData) ** 2 # 计算差值的平方
    distSquareSums = distSquareMat.sum(axis=1) # 求每一行的差值平方和
    distances = distSquareSums ** 0.5 # 开根号，得出每个样本到测试点的距离
    sortedIndices = distances.argsort() # 排序，得到排序后的下标
    indices = sortedIndices[:k] # 取最小的k个
    labelCount = {} # 存储每个label的出现次数
    for i in indices:
        label = labels[i]
        labelCount[label] = labelCount.get(label, 0) + 1 # 次数加一
    sortedCount = sorted(labelCount.items(), key=opt.itemgetter(1), reverse=True)
    # 对label出现的次数从大到小进行排序
    return sortedCount[0][0] # 返回出现次数最大的label

if __name__ == "__main__":
    dataSet = np.array([[2, 3,4], [6, 8,7]])
    normDataSet, ranges, minVals = normData(dataSet)
    labels = ['a', 'b']
    testData = np.array([3.9, 5.5,2])
    normTestData = (testData - minVals) / ranges
    result = kNN(normDataSet, labels, normTestData, 1)
    print(result)

# def get_preknn(l):
#     t = l[5]
#     l[5] = l[4]
#     l[4] = l[3]
#     l[3] = t
#
#
#
#     return mm